package com.aaa.marketresearch.dataresource.domain;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Nail
 */

@Entity
@Table(name = "\"BILL\"")
public class Bill implements Serializable {

    private static final String DATE_FORMAT = "dd-MM-yyyy";
    private static final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    private static final Logger log = LoggerFactory.getLogger(Bill.class);

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "\"BILL_id_seq\"")
    @SequenceGenerator(name = "\"BILL_id_seq\"", sequenceName = "\"BILL_id_seq\"")
    @Column(name = "\"id\"", nullable = false)
    private Integer id;

    @OneToMany(mappedBy="bill",cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private List<BillContent> content;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "\"created\"")
    private Date created;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public List<BillContent> getContent() {
        return content;
    }

    public void setContent(List<BillContent> content) {
        this.content = content;
    }

    public JSONObject getJSON() {
        JSONObject json = new JSONObject();
        json.put("id", this.id);
        json.put("created", dateFormat.format(this.created));

        JSONArray array = new JSONArray();

        List<BillContent> contents = this.content;
        for (BillContent bc : content) {
            array.add(bc.getJSON());
        }

        json.put("content", array);
        return json;
    }

    public Bill() {
        created = new Date();
    }

}
